package priv.wangy.micro.common.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import priv.wangy.micro.common.exception.ServiceException;
import priv.wangy.micro.common.po.http.rspn.BaseHttpResponse;
import priv.wangy.micro.common.po.http.rspn.code.SysErrorEnum;

/**
 * 拦截器 判断请求参数
 *
 * @author wangy
 * @since 2023-10-17
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionInterceptor {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public BaseHttpResponse exceptionHandler(Exception e) {
        BaseHttpResponse response = new BaseHttpResponse();
        StringBuilder sb = new StringBuilder();
        if (e instanceof BindException) {
            for (FieldError fieldError : ((BindException) e).getBindingResult().getFieldErrors()) {
                sb.append(fieldError.getDefaultMessage()).append("!");
            }
            log.error("入参异常：{}", sb);
            response.failure(SysErrorEnum.INVALID_REQUEST_DATA.getRspnCode(), sb.toString());
        } else if (e instanceof ServiceException exception) {
            log.error("业务异常:{},错误码:{},异常消息：{}", exception.getError().toString(), exception.getError().getRspnCode(), exception.getError().getRspnMsg());
            response.failure(((ServiceException) e).getError().getRspnCode(), e.getMessage());
        } else {
            log.error(e.getMessage());
            e.printStackTrace();
            response.failure(SysErrorEnum.INTERNAL_SYSTEM_ERROR.getRspnCode(), SysErrorEnum.INTERNAL_SYSTEM_ERROR.getRspnMsg() + ":" + e.getMessage());
        }
        return response;
    }

}
